package com.darren.center.shardingjdbc.demo.config;

import com.darren.center.shardingjdbc.demo.constants.SysConstant;
import com.darren.center.shardingjdbc.demo.entity.SystemConfigEntity;
import com.darren.center.shardingjdbc.demo.service.ISystemConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;
import java.util.List;

/**
 * Author: 01403292
 * Date: 2021-08-05 13:49:01
 * Version: 1.0
 * Description: 自定义分片规则
 * https://www.jianshu.com/p/4a117a83e249
 */
@Slf4j
public class ShardingRuleStrategy implements PreciseShardingAlgorithm {

    @Override
    public String doSharding(Collection collection, PreciseShardingValue preciseShardingValue) {
        log.info("collection:{}, preciseShardingValue:{}", collection, preciseShardingValue);
        ISystemConfigService systemConfigService = ApplicationContextSupport.getBean(ISystemConfigService.class);
        List<SystemConfigEntity> list = systemConfigService.lambdaQuery().in(SystemConfigEntity::getConfigKey, collection).list();
        for (SystemConfigEntity systemConfigEntity : list) {
            if (systemConfigEntity.getConfigValue().contains(preciseShardingValue.getValue().toString())){
                return systemConfigEntity.getConfigKey();
            }
        }
        return SysConstant.DATE_SOURCE_1;
    }
}
